$(document).ready(function () {
  var base = $("base")[0].href;
	$.ajax({
        type: 'POST',
        async: false,
        url: base+'repository/database/getSimpleList.shtml',
        data: {},
        success: function (data) {
        	for (var i=0; i<data.length; i++){
        		$("#jobRepositoryId").append('<option value="' + data[i].repositoryId + '">' + data[i].repositoryName + '</option>');
        	}
        },
        error: function () {
            alert("请求失败！请刷新页面重试");
        },
        dataType: 'json'
    });
    $.ajax({
        type: 'POST',
        async: false,
        url: base+'category/getSimpleList.shtml',
        data: {},
        success: function (data) {
            for (var i=0; i<data.length; i++){
                $("#categoryId").append('<option value="' + data[i].categoryId + '">' + data[i].categoryName + '</option>');
            }
        },
        error: function () {
            alert("请求失败！请刷新页面重试");
        },
        dataType: 'json'
    });
	  $.ajax({
          type: 'POST',
          async: false,
          url: base+'quartz/getSimpleList.shtml',
          data: {},
          success: function (data) {
          	for (var i=0; i<data.length; i++){
          		$("#jobQuartz").append('<option value="' + data[i].quartzId + '">' + data[i].quartzDescription + '</option>');
          	}
          },
          error: function () {
              alert("请求失败！请刷新页面重试");
          },
          dataType: 'json'
    });
    //输入/出源
    $.ajax({
      type: 'POST',
      async: false,
      url: base+'repository/database/getDatabase.shtml',
      data: {},
      success: function (data) {
        for (var i=0; i<data.length; i++){
          var rDatabase = new String();
          rDatabase = data[i].idDatabase+"_"+data[i].name;
          $("#inputsourceIds").append('<option value="' + rDatabase + '">' + data[i].name + '</option>');
          $("#outputsourceIds").append('<option value="' + rDatabase + '">' + data[i].name + '</option>');
        }
      },
      error: function () {
        alert("请求失败！请刷新页面重试");
      },
      dataType: 'json'
    });
    //下拉多选框
    selectMultip = {
      register: function(id) {
        var dataArr = document.querySelectorAll("[multip]");
        for (var i = 0;i<dataArr.length;i++) {
          render(dataArr[i]);
        }
      },
      reload: function(id, data, setData) {
        var htm = "";
        for(var i = 0; i < data.length; i++) {
          htm += '<option value="' + data[i].value + '">' + data[i].text + '</option>'
        }
        var e = document.getElementById(id);
        e.innerHTML = htm;
        render(e);
        this.setVal(id, setData);
      },
      setVal: function(id, str) {
        var type = Object.prototype.toString.call(str);
        switch(type) {
          case "[object String]":
            document.getElementById(id).val = str;
            break;
          case "[object Array]":
            document.getElementById(id).val = str.toString();
            break;
          default:
            break;
        }
      },
      getVal: function(id) {
        return document.getElementById(id).val;
      },
    };

    selectMultip.register();
	  reset(selectMultip);
});

var reset = function(selectMultip){
	var jobId = $("#jobId").val();
  var base = $("base")[0].href;
	$.ajax({
        type: 'POST',
        async: false,
        url: base+'job/getJob.shtml',
        data: {
        	jobId : jobId
        },
        success: function (data) {
        	var job = data.data;
        	$("#jobRepositoryId").find("option[value=" + job.jobRepositoryId + "]").prop("selected",true);
        	$("#jobPath").val(job.jobPath);
            $("#categoryId").find("option[value=" + job.categoryId + "]").prop("selected",true);
        	$("#jobName").val(job.jobName);
        	$("#jobQuartz").find("option[value=" + job.jobQuartz + "]").prop("selected",true);
        	$("#jobLogLevel").find("option[value=" + job.jobLogLevel + "]").prop("selected",true);
        	$("#jobDescription").val(job.jobDescription);
        	//回显数据源数据
          var inputsourceIdsArr = job.inputsourceIds.split(",");
          var inputsourceNamesArr = job.inputsourceNames.split(",");
          var newIds = "";
          for (var i=0; i<inputsourceIdsArr.length; i++){
              newIds += inputsourceIdsArr[i]+"_"+inputsourceNamesArr[i]+",";
          }
          var outputsourceIdsArr = job.outputsourceIds.split(",");
          var outputsourceNamesArr = job.outputsourceNames.split(",");
          var newOutIds = "";
          for (var i=0; i<outputsourceIdsArr.length; i++){
            newOutIds += outputsourceIdsArr[i]+"_"+outputsourceNamesArr[i]+",";
          }
          selectMultip.setVal("inputsourceIds",newIds.substr(0,newIds.length-1));
          selectMultip.setVal("outputsourceIds",newOutIds.substr(0,newOutIds.length-1));
        },
        error: function () {
            alert("请求失败！请刷新页面重试");
        },
        dataType: 'json'
    });
}

// $("#changeQuartz").click(function(){
// 	$("#default").toggle();
// 	$("#custom").toggle();
// 	$("#jobQuartz").val("");
// 	$("#customerQuarz").val("");
// });
$.validator.setDefaults({
	highlight: function (element) {
        $(element).closest('.form-group').removeClass('has-success').addClass('has-error');
    },
    success: function (element) {
        element.closest('.form-group').removeClass('has-error').addClass('has-success');
    },
    errorElement: "span",
    errorPlacement: function (error, element) {
        if (element.is(":radio") || element.is(":checkbox")) {
            error.appendTo(element.parent().parent().parent());
        } else {
            error.appendTo(element.parent());
        }
    },
    errorClass: "help-block m-b-none",
    validClass: "help-block m-b-none"	
});
$().ready(function () {
    var icon = "<i class='fa fa-times-circle'></i> ";
    var base = $("base")[0].href;
    $("#RepositoryJobForm").validate({
        rules: {
        	jobName: {
        		required: true,
        		maxlength: 50
        	},
            categoryId:{
                required: true
            },
            jobQuartz:{
                required: true
            },
        	jobLogLevel: {
        		required: true,
        	},
        	jobDescription: {
        		maxlength: 500
        	}
        },
        messages: {
        	jobName: {
        		required: icon + "请输入作业名称",
        		maxlength: icon + "作业名称不能超过50个字符"
        	},
            categoryId:{
                required: icon + "请选择作业分类"
            },
            jobQuartz:{
                required: icon + "请选择作业执行策略"
            },
        	jobLogLevel: {
        		required: icon + "请选择作业的日志记录级别",
        	},
        	jobDescription: {
        		maxlength: icon + "作业描述不能超过500个字符"
        	}
        },
        submitHandler:function(form){
        	$.post(base+"job/update.shtml", decodeURIComponent($(form).serialize(),true), function(data){
        		var result = JSON.parse(data);
    			if(result.status == "success"){
    				layer.msg('更新成功',{
            			time: 2000,
            			icon: 6
            		});              		
            		setTimeout(function(){
            			location.href = base+"view/job/listUI.shtml";
            		},2000);
    			}else {
    				layer.msg(result.message, {icon: 2}); 
    			}
    		});
        } 
    });
});

var cancel = function(){
  var base = $("base")[0].href;
	location.href = base+"view/job/listUI.shtml";
}

function render(e) {
  e.param = {
    arr: [],
    valarr: [],
    opts: []
  };
  var choosevalue = "",
    op;

  for(var i = 0; i < e.length; i++) {
    op = e.item(i);
    e.param.opts.push(op);
    if(op.hasAttribute("choose")) {
      if(choosevalue == "") {
        choosevalue = op.value
      } else {
        choosevalue += "," + op.value;
      }

    }
  }

  //创建一个隐藏的option标签用来存储多选的值，其中的值为一个数组
  var option = document.createElement("option");
  option.hidden = true;
  e.appendChild(option);
  e.removeEventListener("change", selchange);
  e.addEventListener("change", selchange);

  //重新定义标签基础属性的get和set方法，实现取值和赋值的功能
  Object.defineProperty(e, "val", {
    get: function() {
      return this.querySelector("[hidden]").value;
    },
    set: function(value) {
      e.param.valarr = [];
      var valrealarr = value == "" ? [] : value.split(",");
      e.param.arr = [];
      e.param.opts.filter(function(o) {
        o.style = "";
      });
      if(valrealarr.toString()) {
        for(var i = 0; i < valrealarr.length; i++) {
          e.param.opts.filter(function(o) {
            if(o.value == valrealarr[i]) {
              o.style = "color: blue;";
              e.param.arr.push(o.text);
              e.param.valarr.push(o.value)
            }
          });
        }
        this.options[e.length - 1].text = e.param.arr.toString();
        this.options[e.length - 1].value = e.param.valarr.toString();
        this.options[e.length - 1].selected = true;
      } else {
        this.options[0].selected = true;
      }

    },
    configurable: true
  })
  //添加属性choose 此属性添加到option中用来指定默认值
  e.val = choosevalue;
  //添加属性tip 此属性添加到select标签上
  if(e.hasAttribute("tip") && !e.tiped) {
    e.tiped = true;
    e.insertAdjacentHTML('afterend', '<i style="color: red;font-size: 12px">*可多选</i>');
  }
};

function selchange() {
  var text = this.options[this.selectedIndex].text;
  var value = this.options[this.selectedIndex].value;
  this.options[this.selectedIndex].style = "color: blue;";
  var ind = this.param.arr.indexOf(text);
  if(ind > -1) {
    this.param.arr.splice(ind, 1);
    this.param.valarr.splice(ind, 1);
    this.param.opts.filter(function(o) {
      if(o.value == value) {
        o.style = "";
      }
    });
  } else {
    this.param.arr.push(text);
    this.param.valarr.push(value);
  }
  this.options[this.length - 1].text = this.param.arr.toString();
  this.options[this.length - 1].value = this.param.valarr.toString();
  if(this.param.arr.length > 0) {
    this.options[this.length - 1].selected = true;
  } else {
    this.options[0].selected = true;
  }
};